# -*- coding:utf-8 -*-
"""
@Author : 审心
@Time : 2023/3/25 15:47
链接工具类
"""


def parse_url(url: str) -> dict:
    """
        解析链接 \n
    :param url: 链接 \n
    :return: 链接字典  \n
    """
    str_s = url.split("?", 1)
    dict_ = {"link": str_s[0], "params": {}}
    if len(str_s) > 1:
        params = str_s[1].split("&")
        if len(params) > 0:
            param_dict = {}
            for e in params:
                s = e.split("=", 1)
                if len(e) > 1:
                    param_dict[s[0]] = s[1]
            if len(param_dict) > 0:
                dict_["params"] = param_dict
    return dict_


def url_dict_to_url(url_dict: dict):
    """
        超链接字典回转 url 字符串
    :param url_dict:
    :return:
    """
    link = url_dict["link"]
    params = url_dict["params"]
    keys = url_dict["params"].keys()
    index = 0
    if len(keys) > 1:
        link += "?"
        for e in keys:
            if index > 0:
                link += "&"
            link += str(e) + "=" + str(params[e])
            index = index + 1
    return link


def url_set_params(old_url: str, uri_param):
    """
    设置链接参数 \n
    :param old_url: 链接 \n
    :param uri_param: 新的链接参数(字典 按序设置) \n
    :return: 新的链接 \n
    """
    url_dict = parse_url(old_url)
    params = url_dict["params"]
    keys = uri_param.keys()
    for e in keys:
        params[e] = uri_param[e]
    return url_dict_to_url(url_dict)


def url_get_params(url: str, key: str):
    """
    获取url中的参数
    :param url: 链接
    :param key: 参数名称
    :return: 参数
    """
    return parse_url(url).get("params").get(key)
